class Cartasur::Location < Cartasur::CartasurModel
  # @rgeo_factory_generator = RGeo::Geos.factory_generator(:srid => 4326)
  set_rgeo_factory_for_column(:coordinates, RGeo::Geographic.spherical_factory(:srid => 4326))

  #has_many :objectives, :class_name => 'Cartasur::Objective'

  attr_accessible :locationtype, :name, :district, :coordinates

   def initialize(args=nil)
     super(args)
     @geographic_factory = RGeo::Geographic.spherical_factory(:srid => 4326)
   end

  def add_coordinates(latlng)
    if @geographic_factory .nil?
      @geographic_factory = RGeo::Geographic.spherical_factory(:srid => 4326)
    end
    # if location is lat,lng coordinates
    latlng =~ /(.*),(.*)/ ?
        (
          str = latlng.split(",")
          self.coordinates =  @geographic_factory.point(str[0], str[1])):
        (latlng.class == Hash) ?
            self.coordinates = @geographic_factory.point(latlng[:lat], latlng[:lng]) :
            self.coordinates = @geographic_factory.point(48.82222, 2.33833)
  end

  def aslatlng
    unless self.coordinates.nil?
      ret = self.coordinates.x.to_s << "," <<self.coordinates.y.to_s
    else
      ret = "48.82222,2.33833"
    end
    ret
  end
end